package com.gqb.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FtpFileCopy {
	public static void main(String[] args) {
		FTPClient ftpClient=new FTPClient();
		try {
			int reply;
			ftpClient.connect("127.0.0.1", 211);
			ftpClient.login("admin", "gqb101112");
			reply=ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
			}
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			ftpClient.setControlEncoding("gbk");
			String toPath="/doc";
			String fromPath="/doc1";
			String filename="5.tif";
			String localPath="d://";
			boolean res = ftpClient.changeWorkingDirectory(getPath(fromPath.replace("//",
					"/"), "iso-8859-1"));
			FTPFile[] files = ftpClient.listFiles();
			int i = 0;
			for (FTPFile ftpFile : files) {
				if (ftpFile.getName().toLowerCase().equals(filename.toLowerCase())) {
					System.out.println(ftpFile.getName());
					File locaFile = new File(localPath + "/" + filename);
					if (!locaFile.getParentFile().exists())
						locaFile.getParentFile().mkdirs();
					OutputStream out = new FileOutputStream(locaFile);
					// 注意此处retrieveFile的第一个参数由GBK转为ISO-8859-1编码。否则下载后的文件内容为空。
					// 原因可能是由于aix系统默认的编码为ISO-8859-1
					ftpClient.retrieveFile(
							new String(ftpFile.getName().getBytes("utf-8"),
									"ISO-8859-1"), out);
					out.close();
				}
				i++;
			}
			boolean res1 = ftpClient.changeWorkingDirectory(getPath(toPath.replace("//",
					"/"), "iso-8859-1"));
			
			FileInputStream in=new FileInputStream(new File(localPath+filename));
			System.out.println("上传"
					+ ftpClient.storeFile(new String(filename.getBytes("utf-8"),
							"iso-8859-1"), in));
			in.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	/**
	 * 返回支持中文的的编码路径
	 * @param path
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private static String getPath(String path,String encodeingType) throws UnsupportedEncodingException{
		return new String(path.getBytes("utf-8"),encodeingType);
	}
	
}
